<script setup>
import { onMounted, ref } from 'vue'
import { getTeahProjList,addTeachProj,deleteTeachProj,changeTeachProj,getApprovalRecordList,deleteFile } from '@/api/teacher/teacher.js'
import { getAchievementLevel } from '@/api/router/achievementLevel'
import { useUserStore } from '@/stores'
import { NBadge, NButton,useMessage } from 'naive-ui'
import { getAllUser } from "@/api/user/user.js"
import { baseURL } from "@/utils/request.js"
/* 审核消息通知 */
//通过 defineEmits编译器宏生成emit方法
const emit = defineEmits(['update-mark'])
const sendType = () => {
  emit('update-mark','teachingProject')
}
/*获取成果级别列表*/
const typeOptions = ref()
const getLevel = async() => {
  const { data:res } = await getAchievementLevel()
  if(res.code === 1) {
    typeOptions.value = res.data.map(item => ({label:item.level,value:item.id}))
  }
  else if( res.code === 0) {
    message.error(res.msg)
  }
}
//调用获取成果级别方法
getLevel()
/* 分页 */
const currentPage = ref(1)
const page_size = ref(10)
const itemCount = ref(null)
const onUpdatePage = async() => {
  if (searchYear.value != null) {
    const startTime = formatTime(searchYear.value[0])
    const endTime = formatTime(searchYear.value[1])
    formValue.value.startTime = startTime
    formValue.value.endTime = endTime
  } else {
    formValue.value.startTime = null
    formValue.value.endTime = null
  }
  formValue.value.pageSize = page_size.value
  formValue.value.page = currentPage.value
  const { data:res } = await getTeahProjList(formValue.value)
  if (res.code  === 1) {
    data.value = res.data.rows
    itemCount.value = res.data.total
  }
  else if(res.code === 0) {
    message.error(res.msg)
  }
}
/*获取教师教学项目列表*/
const data = ref([])  //存储向后端请求回来的教学项目列表数据
const userStore = useUserStore()
const getData = async() => {
  const jobNumber = userStore.jobNumber
  const pageSize = page_size.value
  const roleId = userStore.roleId
  const { data:res } = await getTeahProjList({roleId,jobNumber,pageSize})
  if (res.code  === 1) {
    data.value = res.data.rows
    itemCount.value = res.data.total
  }
  else if(res.code === 0) {
    message.error(res.msg)
  }
}
//调用获取教师教学项目列表
getData()
//---表格信息---
const check = {title:'审核',key:'check',align:'center',filter: true,filterOptionValues: [],
  filterOptions: [{label:'待提交',value: 1},{label:'待初审',value: 2},{label:'待复核',value: 3},{label:'通过',value: 4},
    {label:'驳回修改',value: 5},{label:'不予认定',value: 6}],
  render:row => {
    return [h(NButton,{
          size: 'small',type:'info',quaternary:true,onClick: async() => {
            if(row.mark === 1)  {
              sendType() //如果当前记录为标记记录，则触发时间让菜单栏标记数减1
              changeMark(row.codeNumber) //将当前记录的标记值置为0
            }
            if(row.status === "待提交") {
              current.value = 1
              currentStatus.value = "process"
              step1.value = "请提交申请"
              step2.value = null
              step3.value = null
              step4.value = null
            } else if(row.status === "待初审") {
              current.value = 2
              currentStatus.value = "process"
              step1.value = "已提交申请"
              step2.value = "审核中"
              step3.value = null
              step4.value = null
            } else if(row.status === "待复核") {
              current.value = 3
              currentStatus.value = "process"
              step1.value = "已提交申请"
              step2.value = "通过"
              step3.value = "审核中"
              step4.value = null
            } else if(row.status === "通过") {
              current.value = 4
              currentStatus.value = "process"
              step1.value = "已提交申请"
              step2.value = "通过"
              step3.value = "通过"
              step4.value = "项目审核完成"
            }
            else if(row.status === "驳回修改" || row.status === "不予认定") {
              const achievementId = row.codeNumber
              const { data: res } = await getApprovalRecordList({achievementId})
              if(res.code === 1) {
                approvalRecord.value = res.data[0]
                if(approvalRecord.value.phase === "初审") {
                  current.value = 2
                  currentStatus.value = "error"
                  step1.value = "已提交申请"
                  step2.value = approvalRecord.value.opinion
                  step3.value = null
                  step4.value = null
                } else if(approvalRecord.value.phase === "复核") {
                  current.value = 3
                  currentStatus.value = "error"
                  step1.value = "已提交申请"
                  step2.value = "通过"
                  step3.value = approvalRecord.value.opinion
                  step4.value = null
                }
              } else message(res.msg)
            }
            showCheckModal.value=true
          }
        },
        {default: () => row.status}
    ),
      row.mark === 1 ? h(NBadge,{type: 'warning', dot: true,}, {default: () => {}}) : ''
    ]
  }}
const level = {title:'级别',key:'level',align:"center",filter: true,filterOptionValues: [],filterOptions: [{label: '国家级',value: 1},
    {label: '省部级',value: 2},{label: '厅局级',value: 3},{label: '校级',value: 4}]}
const columns=[
  {title:'序号',key:'key',render:(_,index)=>`${index + 1}`,align:"center"},
  {title:'项目名称',key:'projectName',align:"center"},
  level,
  {title:'立项时间（年/月）',key:'year' ,align:"center"},
  {title:'项目负责人',key:'leader' ,align:"center"},
  {title:'其他成员',key:'others' ,align:"center"},
  {title:'相关附件',key:'attachment',align:'center',width:'200',render:row => {
      if(row.attachment != null) {
        let attachmentArray = row.attachment.split(',')
        const displayArray = ref([])
        attachmentArray.forEach((item,index) => {
          displayArray.value.push (h(NButton,{
                size: 'small', type:'info', quaternary: true, onClick: () => {
                  const url = baseURL + item
                  window.open(url,"_blank")
                }
              },
              {default: () => '附件'+ `${index + 1}`}
          ))
        })
        return displayArray.value
      }
    }},
  {title:'备注',key:'comment' ,align:"center"},
  check,
  {title:'操作',key:'operate' ,align:"center",width:'200',render:row=>{
      if(row.statusId === 1 || row.statusId === 5 || row.statusId === 6 ) {
        return [
          h(NButton,{
                size: 'small', type: 'primary', secondary: true, onClick: () => {
                  showChangeModal.value=true;
                  size.value = 0  //将用来计算文件大小的size置为0
                  getUser() //获取全部用户数据
                  changePathArray.value = []  //将用来重新上传后用到存储地址的数组置为空
                  changeForm.value.codeNumber=row.codeNumber;
                  changeForm.value.projectName=row.projectName;
                  changeForm.value.achievementLevelId=row.achievementLevelId;
                  if(row.year != null) {
                    changeForm.value.changeYear =Date.parse(row.year)
                  } else {
                    changeForm.value.changeYear = null
                  }
                  changeForm.value.year = null
                  changeForm.value.leader=row.leader;
                  if(row.attachment !== null) changePathArray.value = row.attachment.split(',')
                  fileList.value = changePathArray.value.map((item,index) => ({id: index,name: '附件' + (index + 1),status: 'finished', url: baseURL + item}))
                  //将修改模态框中其他成员的数组置空，将数据进行处理重新渲染
                  changeCustomValue.value = []
                  let nameArray = []
                  let jobNumberArray = []
                  if(row.others !== null) nameArray = row.others.split('，')
                  if(row.otherJobNumber !== null) jobNumberArray = row.otherJobNumber.split(',')
                  jobNumberArray.forEach((item,index) => {
                    if(item === 'null') {
                      changeCustomValue.value.push({identify: '院外', name: nameArray[index]})

                    }else if(item === ''){ return }
                    else {
                      changeCustomValue.value.push({identify: '院内', name: nameArray[index] + ',' + item})
                    }
                  })
                  changeForm.value.comment=row.comment;
                }
              },{default:()=>('修改')}
          ),
          h(NButton,{
                size: 'small', type: 'error', secondary: true, onClick: async() => {
                  dialog.value=true
                  dialogProjectNumber.value = row.codeNumber
                  dialogAttachment.value = row.attachment
                }
              },
              {default:()=>('删除')}
          ),
          h(NButton,{
                size: 'small', type: 'info', secondary: true, onClick: async() => {
                  let msg = ''
                  if(row.projectName === null) msg  += '项目名称为空;'
                  if(row.achievementLevelId === null) msg  += '级别为空;'
                  if(row.year === null) msg  += '立项时间（年/月）为空;'
                  if(row.leader === null) msg  += '项目负责人为空;'
                  // if(row.others === null) msg  += '其他成员为空;'
                  if(row.attachment === null) msg  += '相关附件为空;'
                  if(msg === '') {
                    const temp = {
                      codeNumber: row.codeNumber,
                      statusId: 2
                    }
                    const {data:res} = await await changeTeachProj(JSON.stringify(temp))
                    if(res.code === 1) {
                      message.success('提交成功')
                    } else message.error(res.msg)
                  } else message.error(msg)
                  onUpdatePage()
                }
              },
              {default:()=>('提交')}
          )
        ]
      }
      else{
        return h(NButton,{
              size: 'small', type: 'primary', secondary: true, onClick: () => {
                showViewModal.value=true;
                viewForm.value.projectName=row.projectName;
                viewForm.value.level=row.level;
                viewForm.value.year = row.year
                viewForm.value.leader=row.leader;
                viewForm.value.attachment=row.attachment;
                addPathArray.value = []
                if(row.attachment !== null) addPathArray.value = row.attachment.split(',')  //将当前记录的附件字符串转换为数组
                viewForm.value.others=row.others;
                viewForm.value.otherJobNumber=row.otherJobNumber;
                othersData.value= [];
                let nameArray = []
                let jobNumberArray = []
                if(row.others !== null) nameArray = viewForm.value.others.split('，');
                if(row.otherJobNumber !== null) jobNumberArray = viewForm.value.otherJobNumber.split(',');
                nameArray.forEach((item,index) => {
                  if(jobNumberArray[index] === 'null') {
                    othersData.value.push({type: '院外',name: item,jobNumber: null})
                  } else {
                    othersData.value.push({type: '院内',name: item,jobNumber: jobNumberArray[index]})
                  }
                })
                viewForm.value.comment=row.comment;
              }
            },{default:()=>('查看')}
        )
      }
    }},
]

/* 项目过滤 */
const checkReactive = reactive(check)
const checkFilterValues = ref([])
const levelReactive = reactive(level)
const levelFilterValues = ref([])
const handleFiltersChange = (filters) => {
  //审核
  checkFilterValues.value = filters.check || []
  checkReactive.filterOptionValues = checkFilterValues.value
  checkFilterValues.value = checkFilterValues.value.toString()
  //级别
  levelFilterValues.value = filters.level || []
  levelReactive.filterOptionValues = levelFilterValues.value
  levelFilterValues.value = levelFilterValues.value.toString()
  searchAchievement()
}

//删除确认
const dialogProjectNumber = ref('')
let dialogAttachment =ref('')
const dialog = ref(false)
const handleNegativeClick=()=>{
  message.warning("取消");
  dialog.value=false
}
const handlePositiveClick=async()=> {
  const id = dialogProjectNumber.value
  const path = dialogAttachment.value
  await deleteFile({path})  //先删除相关附件
  const { data:res } = await deleteTeachProj(id)
  if(res.code === 1) {
    message.success('删除成功')
  } else {
    message.error('删除失败')
  }
  onUpdatePage()
  dialog.value=false
}

/*添加教学项目模态框*/
const showAddModal = ref(false)
const addFormRef=ref(null)
//获取表项中收集到的值的对象
const addForm=ref({
  middleYear:null,
  projectName:null,
  achievementLevelId: null,
  year: null,
  leader: null,
  others: null,
  attachment: null,
  comment: null,
  jobNumber: userStore.jobNumber,
  otherJobNumber: null
})
//验证表项的规则
const formRules={
  projectName:{required: true, message: '请填写项目名称', trigger: 'blur'},
  achievementLevelId:{type: "number",required: true, message: '请选择项目类别', trigger: 'blur'},
  middleYear:{type: "number",required: true, message: '请填写立项时间（年/月）', trigger: 'blur'},
  leader:{required: true, message: '请填写项目负责人', trigger: 'blur'},
  attachment:{required: true, message: '请填写相关附件', trigger: 'blur'},
}

const addProject = () => {
  showAddModal.value = true
  customValue.value = []
  addPathArray.value = []
  getUser()
  //将表单项的值先制空
  addForm.value.middleYear=null
  addForm.value.projectName = null
  addForm.value.achievementLevelId = null
  addForm.value.year = null
  addForm.value.middleYear=null
  addForm.value.leader = null
  addForm.value.others = null
  addForm.value.otherJobNumber = null
  addForm.value.attachment = null
  addForm.value.comment = null

}

/*文件上传*/
const size = ref(0)
//文件上传前的校验方法
const beforeUpload = (data) => {
  if(data.file.file?.type === 'image/jpeg' || data.file.file?.type === 'image/png' || data.file.file?.type === 'image/bmp' || data.file.file?.type === 'application/pdf') {
    size.value += data.file.file.size
    if(size.value > 31457280) {
      message.error('大小限制在30M以内,请重新上传')
      return false
    }
    return true
  }
  message.error('只能上传jpg、bmp、png、pdf等文件,请重新上传')
  return false
}


//上传文件
//添加
const message = useMessage()
const addPathArray = ref([])
//文件上传结束的回调
const handleFinish = ({file,event}) => {
  let path = JSON.parse(event.target.response)
  path = path.data[0]
  file.url = baseURL + path
  addPathArray.value.push(path)
  message.success('上传成功')
}
//文件删除回调
const handelRemove = async(options) => {
  let path = options.file.url
  path = path.replace(baseURL,'')
  if(path !== null && path !== '') {
    const { data:res } = await deleteFile({path})
    if(res.code === 1) {
      addPathArray.value.splice(addPathArray.value.indexOf(path),1)
      message.success('删除成功')
      return true
    }
    message.error('删除失败')
    return false
  }
  return true
}
//修改
const fileList = ref([])
const changePathArray = ref([])
const handleChangeFinish = ({file,event}) => {
  let path = JSON.parse(event.target.response)
  path = path.data[0]
  file.url = baseURL + path
  changePathArray.value.push(path)
  message.success('上传成功')
}
//文件删除回调
const handelChangeRemove = async(options) => {
  let path = options.file.url
  if(path !== null && path !== '') {
    path = path.replace(baseURL,'')
    const { data:res } = await deleteFile({path})
    if(res.code === 1) {
      changePathArray.value.splice(changePathArray.value.indexOf(path),1)
      message.success('删除成功')
      return true
    }
    message.error('删除失败')
    return false
  }
  return true
}

//获取当前时间
const now=new Date()
/* 保存教学项目 */
const saveAdd = async() => {
  //将时间戳改为年份
  if( addForm.value.middleYear != null&& addForm.value.year ===null) {
    const date = new Date(addForm.value.middleYear)
    const year = date.getFullYear()
    const month = (date.getMonth() + 1).toString().padStart(2, '0'); // 获取月份并补零
    const day = date.getDate().toString().padStart(2, '0'); // 获取日期并补零
    const formattedDate = `${year}-${month}-${day}`;
    addForm.value.year = formattedDate;
    if(year>now.getFullYear()){
      alert("请输入有效时间")
      addForm.value.middleYear=null
      addForm.value.year= null
    }
  }
  //将参与人员名字和工号提取出来
  const names = ref('')
  const jobNumbers = ref('')
  if(customValue.value.length !== 0) {
    customValue.value.forEach(item => {
      if(item.identify === '院内') {
        if(names.value === '') {
          names.value = item.name.substring(0,item.name.indexOf(','))
        } else{
          names.value += '，'
          names.value += item.name.substring(0,item.name.indexOf(','))
        }
        if(jobNumbers.value === '') {
          jobNumbers.value = item.name.substring(item.name.indexOf(',') + 1)
        }
        else {
          jobNumbers.value += ','
          jobNumbers.value += item.name.substring(item.name.indexOf(',') + 1)
        }
      } else{
        if(names.value === '') {
          names.value = item.name
        } else{
          names.value += '，'
          names.value += item.name
        }
        if(jobNumbers.value === '') {
          jobNumbers.value = 'null'
        } else{
          jobNumbers.value += ','
          jobNumbers.value += 'null'
        }
      }
    })
  }
  addForm.value.others = names.value
  addForm.value.otherJobNumber = jobNumbers.value
  addForm.value.attachment = addPathArray.value.toString()
  //对表单项进行非空验证
  let msg = ''
  if(addForm.value.projectName === null||addForm.value.projectName === '') msg  += '项目名称为空;'
  if(addForm.value.achievementLevelId === null) msg  += '级别为空;'
  if(addForm.value.year === null||addForm.value.year === '') msg  += '立项时间（年/月）为空;'
  if(addForm.value.leader === null||addForm.value.leader === '') msg  += '项目负责人为空;'
  if(addForm.value.attachment === null|| addForm.value.attachment === '') msg  += '相关附件为空;'
  if(msg === '') {
    const { data: res } = await addTeachProj(addForm.value)
    if(res.code === 0) message.error(res.msg)
    else{
      onUpdatePage()
      showAddModal.value = false
    }
  }
  else{
    message.error(msg)
  }
}

/* 修改教学项目模态框 */
const showChangeModal = ref(false)
const changeForm = ref({
  changeYear:null,
  codeNumber:null,
  projectName:null,
  achievementLevelId: null,
  year: null,
  leader: null,
  others: null,
  attachment: null,
  comment: null,
  otherJobNumber: null
})
const changeFormRef=ref(null)
const changeFormRules = {
  projectName:{required: true, message: '请填写项目名称', trigger: 'blur'},
  achievementLevelId:{type: "number",required: true, message: '请选择项目类别', trigger: 'blur'},
  changeYear:{type: "number",required: true, message: '请填写立项时间（年/月）', trigger: 'blur'},
  leader:{required: true, message: '请填写项目负责人', trigger: 'blur'},
  // others:{required: true, message: '请填写其他成员', trigger: 'blur'},
  attachment:{required: true, message: '请填写相关附件', trigger: 'blur'},
}
const saveChange = async() => {
  if(changeForm.value.year === null && changeForm.value.changeYear != null) {
    const date = new Date(changeForm.value.changeYear)
    const year = date.getFullYear()
    const month = (date.getMonth() + 1).toString().padStart(2, '0'); // 获取月份并补零
    const day = date.getDate().toString().padStart(2, '0'); // 获取日期并补零
    const formattedDate = `${year}-${month}-${day}`;
    changeForm.value.year = formattedDate;
    if(year>now.getFullYear()){
      alert("请输入有效时间")
      changeForm.value.changeYear=null
      changeForm.value.year = null
    }
  }
  //将参与人员名字和工号提取出来
  const names = ref('')
  const jobNumbers = ref('')
  if(changeCustomValue.value.length !== 0) {
    changeCustomValue.value.forEach(item => {
      if(item.identify === '院内') {
        if(names.value === '') {
          names.value = item.name.substring(0,item.name.indexOf(','))
        } else{
          names.value += '，'
          names.value += item.name.substring(0,item.name.indexOf(','))
        }
        if(jobNumbers.value === '') {
          jobNumbers.value = item.name.substring(item.name.indexOf(',') + 1)
        }
        else {
          jobNumbers.value += ','
          jobNumbers.value += item.name.substring(item.name.indexOf(',') + 1)
        }
      } else{
        if(names.value === '') {
          names.value = item.name
        } else{
          names.value += '，'
          names.value += item.name
        }
        if(jobNumbers.value === '') {
          jobNumbers.value = 'null'
        } else{
          jobNumbers.value += ','
          jobNumbers.value += 'null'
        }
      }
    })
  }
  changeForm.value.others = names.value
  changeForm.value.otherJobNumber = jobNumbers.value
  changeForm.value.attachment = changePathArray.value.toString()
  let msg = ''
  if(changeForm.value.projectName === null||changeForm.value.projectName === '') msg  += '项目名称为空;'
  if(changeForm.value.achievementLevelId === null) msg  += '级别为空;'
  if(changeForm.value.year === null||changeForm.value.year === '') msg  += '立项时间（年/月）为空;'
  if(changeForm.value.leader === null||changeForm.value.leader === '') msg  += '项目负责人为空;'
  // if(changeForm.value.others === '') msg  += '其他成员为空;'
  if(changeForm.value.attachment === null|| changeForm.value.attachment === '') msg  += '相关附件为空;'
  if(msg === '') {
    const temp = JSON.stringify(changeForm.value)
    const {data:res} = await changeTeachProj(temp)
    if(res.code === 0) message.error(res.msg)
    else{
      onUpdatePage()
      showChangeModal.value=false
    }
  }
  else{
    message.error(msg)
  }
}

/* 查看教学项目模态框 */
const showViewModal = ref(false)
const viewForm = ref({
  projectName:null,
  achievementLevelId: null,
  year: null,
  leader: null,
  others: null,
  otherJobNumber: null,
  attachment: null,
  comment: null,
})
const othersColumns = [
  {title:'排名',key:'key',render:(_,index)=>`${index + 1}`,align:"center" },
  {title:'类别',key:'type',align:"center"},
  {title:'姓名',key:'name',align:"center"},
  {title:'工号',key:'jobNumber',align:"center"}
]
const othersData = ref([])

/* 审批进度模态框 */
const showCheckModal = ref(false)
const current = ref(2)
const currentStatus = ref("process")
const step1 = ref(null)
const step2 = ref(null)
const step3 = ref(null)
const step4 = ref(null)
const approvalRecord = ref(null)

//更新标记位方法
const changeMark = async(codeNumber) => {
  let temp = {mark: 0, codeNumber: codeNumber}
  temp = JSON.stringify(temp)
  await changeTeachProj(temp)
  onUpdatePage()
}


/* 条件查询成果信息 */
const searchYear = ref(null)
const formValue = ref({
  jobNumber: userStore.jobNumber,
  projectName: null,
  roleId: userStore.roleId,
  checkFilterValues: checkFilterValues,
  levelFilterValues: levelFilterValues,
  startTime: null,
  endTime: null,
  pageSize: null,
  page: null
})
const searchAchievement = async() => {
  if (searchYear.value != null) {
    const startTime = formatTime(searchYear.value[0])
    const endTime = formatTime(searchYear.value[1])
    formValue.value.startTime = startTime
    formValue.value.endTime = endTime
  } else {
    formValue.value.startTime = null
    formValue.value.endTime = null
  }
  const { data: res } = await getTeahProjList(formValue.value)
  if(res.code === 1) {
    data.value = res.data.rows
    itemCount.value = res.data.total
    currentPage.value = 1
  }
  else if(res.code === 0) {
    message.error(res.msg)
  }
}

/* 将时间戳格式化为年-月-日 */
const formatTime = (time) => {
  const date = new Date(time)
  const year = date.getFullYear()
  const month = (date.getMonth() + 1).toString().padStart(2, '0') // 获取月份并补零
  const day = date.getDate().toString().padStart(2, '0') // 获取日期并补零
  const formattedDate = `${year}-${month}-${day}`
  return formattedDate
}


/* 添加参与人员 */
const nameOptions = ref()
const customValue = ref([
  {
    identify: null,
    name: null,
  }
])
const changeCustomValue = ref([])
const options = [
  {
    label: '院内',
    value: '院内'
  },
  {
    label: '院外',
    value: '院外'
  }
]

const onCreate = () => {
  return {
    identify: '院内',
    name: null,
  }
}

const getUser = async() => {
  const { data: res } = await getAllUser()
  if(res.code === 1) {
    nameOptions.value = res.data.map(item => ({
      label: item.name + ' ' + item.jobNumber,
      value: item.name + ',' + item.jobNumber
    }))
  }
}
//快捷键查询
const selectButtonClicked = () => searchAchievement();

// 添加键盘按下事件监听器
onMounted(() => {
  const handleKeyDown = (event) => {
    if (event.key === "Enter") {
      selectButtonClicked();
    }
  };

  // 注册监听器
  window.addEventListener('keydown', handleKeyDown);

  // 在组件卸载时移除监听器以防止内存泄漏
  onUnmounted(() => {
    window.removeEventListener('keydown', handleKeyDown);
  });
});

/* 院内院外切换时置空 */
const onChange = (value) => {
  value.name = null
}
</script>


<template>
  <div class="title">教学项目信息登记</div>
  <div class="content">
    <div class="function">
      <n-space style="margin-bottom: 5px;">
        <n-form
            inline
            label-placement="left"
            :model="formValue"
            size="small"
        >
          <n-form-item label="项目名称" path="projectName">
            <n-input v-model:value="formValue.projectName" placeholder="输入项目名称" />
          </n-form-item>
          <n-form-item label="时间" path="searchYear">
            <n-date-picker v-model:value="searchYear" type="monthrange" clearable style="width: 200px" />
          </n-form-item>
          <n-form-item>
            <n-button attr-type="button" @click="searchAchievement" type="info" id="selsctButton">
              查询
            </n-button>
          </n-form-item>
        </n-form>
      </n-space>
      <n-space style="margin-bottom: 5px;">
        <n-button type="primary" tertiary @click="addProject" style="padding: 0 4px; font-size: 16px;">
          <template #icon>
            <n-icon>
              <img src="@/assets/edit_add.png" alt="新增" style="height: 16px; margin: 0;">
            </n-icon>
          </template>
          新增
        </n-button>
      </n-space>
    </div>
    <n-data-table
        :columns="columns"
        :data="data"
        bordered
        :single-line="false"
        size='small'
        @update:filters="handleFiltersChange"
    />
    <div class="pagination">
      <n-pagination v-model:page="currentPage"
                    @update-page="onUpdatePage"
                    :page-size="page_size"
                    :item-count="itemCount"/>
    </div>
    <!-- 添加教学项目模态框 -->
    <n-modal v-model:show="showAddModal" :auto-focus="false" :mask-closable="false">
      <n-card style="width: 650px;"
              title="添加教学项目"
              bordered
              closable
              @close="showAddModal=false"
              size="small"
              role="dialog"
              aria-modal="true">
        <n-form :model="addForm"
                ref="addFormRef"
                :rules="formRules"
                style="padding-top: 10px;"
                label-placement="left"
                label-width="100"
                label-align="right">
          <n-form-item label="项目名称" path="projectName">
            <n-input v-model:value="addForm.projectName" clearable />
          </n-form-item>
          <n-form-item label="级别" path="achievementLevelId">
            <n-select v-model:value="addForm.achievementLevelId" placeholder="请选择" :options="typeOptions" />
          </n-form-item>
          <n-form-item label="立项时间（年/月）" path="middleYear">
            <n-date-picker type="date" v-model:value="addForm.middleYear" style="width:550px" format="yyyy-MM-dd"/>
          </n-form-item>
          <n-form-item label="项目负责人" path="leader">
            <n-input v-model:value="addForm.leader" clearable/>
          </n-form-item>
          <n-form-item label="其他成员" path="others">
            <n-dynamic-input v-model:value="customValue" :on-create="onCreate">
              <template #create-button-default>
                添加参与人员
              </template>
              <template #default="{ value }">
                <div style="display: flex; align-items: center; width: 100%">
                  <n-space style="width: 50px;">排名{{ customValue.indexOf(value) + 1 }}</n-space>
                  <n-select v-model:value="value.identify" :options="options" style="width: 100px;" @update:value="onChange(value)"/>
                  <n-select
                      v-if="value.identify === '院内'"
                      v-model:value="value.name"
                      filterable
                      clearable
                      :options="nameOptions"
                  />
                  <n-input
                      v-else
                      v-model:value="value.name"
                      type="text" />
                </div>
              </template>
            </n-dynamic-input>
          </n-form-item>
          <n-form-item label="相关附件" path="attachment" class="fileUpload">
            <n-upload
                ref="uploadRef"
                :action="baseURL + '/upload'"
                :headers="{
                  'Token': userStore.token
                }"
                :multiple="true"
                :max=6
                @finish="handleFinish"
                @before-upload="beforeUpload"
                @remove="handelRemove"
            >
              <n-button>选择文件</n-button>
            </n-upload>
          </n-form-item>
          <n-form-item label="备注" path="comment">
            <n-input v-model:value="addForm.comment" clearable/>
          </n-form-item>
        </n-form>
        <!-- 对话框底部控制按钮 -->
        <template #footer>
          <div style="float: right">
            <n-space>
              <n-button size="small" secondary type="primary" @click="saveAdd">保存</n-button>
              <n-button size="small" secondary @click="showAddModal=false">取消</n-button>
            </n-space>
          </div>
        </template>
      </n-card>
    </n-modal>

    <!-- 删除确认框 -->
    <n-modal
        v-model:show="dialog"
        preset="dialog"
        title="确认"
        content="是否删除"
        positive-text="确认"
        negative-text="取消"
        @positive-click="handlePositiveClick"
        @negative-click="handleNegativeClick"
    />
    <!-- 修改教学项目模态框 -->
    <n-modal v-model:show="showChangeModal" :mask-closable="false">
      <n-card style="width: 650px;"
              title="修改教学项目"
              bordered
              closable
              @close="showChangeModal=false"
              size="small"
              role="dialog"
              aria-modal="true">
        <n-form :model="changeForm"
                ref="changeFormRef"
                :rules="changeFormRules"
                style="padding-top: 10px;"
                label-placement="left"
                label-width="100"
                label-align="right">
          <n-form-item label="项目名称" path="projectName">
            <n-input v-model:value="changeForm.projectName" clearable />
          </n-form-item>
          <n-form-item label="级别" path="achievementLevelId">
            <n-select v-model:value="changeForm.achievementLevelId" :options="typeOptions" />
          </n-form-item>
          <n-form-item label="立项时间（年/月）" path="changeYear">
            <n-date-picker v-model:value="changeForm.changeYear" style="width:550px" format="yyyy-MM-dd"/>
          </n-form-item>
          <n-form-item label="项目负责人" path="leader">
            <n-input v-model:value="changeForm.leader" clearable/>
          </n-form-item>
          <n-form-item label="其他成员" path="others">
            <n-dynamic-input v-model:value="changeCustomValue" :on-create="onCreate">
              <template #create-button-default>
                添加参与人员
              </template>
              <template #default="{ value }">
                <div style="display: flex; align-items: center; width: 100%">
                  <n-space style="width: 50px;">排名{{ changeCustomValue.indexOf(value) + 1 }} </n-space>
                  <n-select v-model:value="value.identify" :options="options" style="width: 100px;" @update:value="onChange(value)"/>
                  <n-select
                      v-if="value.identify === '院内'"
                      v-model:value="value.name"
                      filterable
                      clearable
                      :options="nameOptions"
                  />
                  <n-input
                      v-else
                      v-model:value="value.name"
                      type="text" />
                </div>
              </template>
            </n-dynamic-input>
          </n-form-item>
          <n-form-item label="相关附件" path="attachment"  class="fileUpload">
            <n-upload
                ref="changeUploadRef"
                :action="baseURL + '/upload'"
                :default-file-list="fileList"
                :headers="{
                  'Token': userStore.token
                }"
                :multiple="true"
                :max=6
                @finish="handleChangeFinish"
                @before-upload="beforeUpload"
                @remove="handelChangeRemove"
            >
              <n-button>选择文件</n-button>
            </n-upload>
          </n-form-item>
          <n-form-item label="备注" path="comment">
            <n-input v-model:value="changeForm.comment" clearable/>
          </n-form-item>
        </n-form>
        <!-- 对话框底部控制按钮 -->
        <template #footer>
          <div style="float: right">
            <n-space>
              <n-button size="small" secondary type="primary" @click="saveChange">保存</n-button>
              <n-button size="small" secondary @click="showChangeModal=false">取消</n-button>
            </n-space>
          </div>
        </template>
      </n-card>
    </n-modal>

    <!-- 查看教学项目模态框 -->
    <n-modal v-model:show="showViewModal">
      <n-card style="width: 650px;"
              title="查看教学项目"
              bordered
              closable
              @close="showViewModal=false"
              size="small"
              role="dialog"
              aria-modal="true">
        <n-form style="padding-top: 10px;"
                label-placement="left"
                label-width="100"
                label-align="right">
          <n-form-item label="项目名称:" path="projectName">
            <span>{{ viewForm.projectName }}</span>
          </n-form-item>
          <n-form-item label="级别:" path="level">
            <span>{{ viewForm.level }}</span>
          </n-form-item>
          <n-form-item label="立项时间（年/月）:" path="year">
            <span>{{ viewForm.year }}</span>
          </n-form-item>
          <n-form-item label="项目负责人:" path="leader">
            <span>{{ viewForm.leader }}</span>
          </n-form-item>
          <n-form-item label="其他成员:" path="others">
            <n-data-table
                bordered
                :columns="othersColumns"
                :single-line="false"
                :data="othersData"
                size="small"
            />
          </n-form-item>
          <n-form-item label="相关附件:" path="attachment">
            <a style="margin-right: 5px;" v-for="(item,index) in addPathArray" :key="index" :href = "baseURL+ item" target="_blank">附件{{ index + 1 }}</a>
          </n-form-item>
          <n-form-item label="备注:" path="comment">
            <span>{{ viewForm.comment }}</span>
          </n-form-item>
        </n-form>
      </n-card>
    </n-modal>

    <!-- 审批进度模态框 -->
    <n-modal v-model:show="showCheckModal" preset="dialog" title="Dialog" style="width: 1000px;height: 200px;" >
      <template #header>
        <div style="font-size: 25px;">审核</div>
      </template>
      <div style="margin-top: 30px;">
        <n-space vertical>
          <n-steps :current="Number(current)" :status="currentStatus">
            <n-step
                title="提交"
                :description="step1"
            />
            <n-step
                title="初审"
                :description="step2"
            />
            <n-step
                title="复核"
                :description="step3"
            />
            <n-step
                title="已完成"
                :description="step4"
            />
          </n-steps>
        </n-space>
      </div>
    </n-modal>
  </div>
  <div style="color: red; font-size: 13px;">
    说明：1.附件格式为jpg、bmp、png、pdf等文件
    <br>
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;2.不支持压缩包上传
    <br>
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;3.大小限制在30M以内
  </div>
</template>
<style scoped>
.pagination {
  float: right;
  padding-top: 50px;
}
.title{
  color: rgb(5,93,163);
  text-align: center;
  font-size:22px;
  font-family: "Microsoft Yahei","Helvetica Neue", Helvetica, Arial, sans-serif;
  border-bottom: 1px solid rgb(193, 217, 237);
  margin-bottom: 5px;
}

/* 样式穿透在vue3中的两种写法
第一种
 :deep(.n-data-table-th__title){
   font-weight: 600;
 }*/

/* 第二种 */
::v-deep .n-data-table-th__title{
  font-weight: 600;
}

::v-deep .n-button__icon{
  margin:0 1px 0 0;
}
.fileInput {
  width: 180px;
}

span {
  width: 100%;
  padding: 5px;
  border: 1px solid rgb(184, 182, 182);
  height: 22px;
}
::v-deep .n-data-table-td{
  padding: 6px;
}

.function{
  display: flex;
  justify-content: space-between;
}
::v-deep .fileUpload>.n-form-item-blank{
  display: block;
}
.warn{
  border: 0;
  margin-left: 10px;
  font-size: 13px;
  color: red;
}
</style>
